const User = require('../../models/blog_user'); // 前台用户表
const AdminUser = require('../../models/admin_users'); // 后台用户表
const Role = require('../../models/admin_role'); // 后台角色
const UserOrRole = require('../../models/admin_user_or_role'); // 后台用户角色关联表
const Utils = require('../../utils'); // 工具函数
const authCodeFunc = require('../../utils/authCode');

const Talk = require('../../models/blog_talk'); // 留言表

const knex = require('../../models/knex');

const ControllerTalk = {
    /* 列表 */
    getList: async function (req, res, next) {
        try {
            let { per_page, page } = req.query;

            let users = User.table;
            let adUser = AdminUser.table;
            let roles = Role.table;
            let talks = Talk.table;

            // 后台用户留言
            const admin = await knex(talks)
                .join(adUser, `${talks}.user_id`, `${adUser}.id`)
                .join(roles, `${talks}.role`, `${roles}.id`)
                .select(
                    `${talks}.id`,
                    `${talks}.comment_level`,
                    `${talks}.parent_comment_id`,
                    `${talks}.reply_comment_id`,
                    `${talks}.content`,
                    `${talks}.role`,
                    `${talks}.host`,
                    `${talks}.user_id`,
                    `${talks}.created_time`,
                    `${adUser}.user_name`,
                    `${adUser}.user_account as account`,
                    `${adUser}.user_avatar_url as avatar`,
                    `${roles}.name as role_name`,
                );

            // 前台用户留言
            const web = await knex(talks)
                .join(users, `${talks}.user_id`, `${users}.id`)
                .select(
                    `${talks}.id`,
                    `${talks}.comment_level`,
                    `${talks}.parent_comment_id`,
                    `${talks}.reply_comment_id`,
                    `${talks}.content`,
                    `${talks}.role`,
                    `${talks}.host`,
                    `${talks}.user_id`,
                    `${talks}.created_time`,
                    `${users}.name as user_name`,
                    `${users}.account`,
                    `${users}.avatar_url as avatar`,
                );

            // admin与web合并
            const newTalks = admin.concat(web);

            // 按id升序排序
            newTalks.sort((a, b) => {
                return a.id - b.id
            });

            const getComment = Utils.getData(newTalks); //* 树形数据处理索引0为一级，其他均为子级
            const commentData = Utils.getChildrenTree(getComment, getComment[0]); //* 按父子关系处理分类
            const list = Utils.getPagination(commentData, per_page, page);

            let total = commentData.length; //* 文章总数
            let number = Math.ceil(total / per_page); //* 计算出信息总页数


            res.json({ code: 200, msg: '链接成功', data: { list, total, number } })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 添加留言 */
    Insert: async function (req, res, next) {
        try {
            let { content } = req.body;
            let authorization = req.headers.authorization;
            let user_id = '';

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            } else {
                return res.json({ code: 0, msg: '还未登录' })
            }

            let params = {
                user_id,
                content: encodeURI(content),
                created_time: new Date().getTime()
            }

            await Talk.insert(params);

            res.json({ code: 200, msg: '成功新增留言', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },

    /* 回复 */
    reply: async function (req, res, next) {
        try {
            let { id, content, comment_level } = req.body;
            let authorization = req.headers.authorization;
            let user_id = '';

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            } else {
                return res.json({ code: 0, msg: '还未登录' })
            }

            const talks = await Talk.select({ id });

            let parent_comment_id = talks[0].parent_comment_id; // 父留言id
            let reply_comment_id = id;

            let params = {
                user_id,
                content: encodeURI(content),
                comment_level,
                parent_comment_id: parent_comment_id ? parent_comment_id : id,
                reply_comment_id,
                created_time: new Date().getTime()
            }

            await Talk.insert(params);

            res.json({ code: 200, msg: '成功回复留言', data: {} })
        } catch (e) {
            res.json({ code: 0, data: e })
        }
    },
}

module.exports = ControllerTalk;